<template>
	<view class="form-y-table">
		<view style="width: 100%;">
			<y-table :scroll="keys.scroll" :headers="keys.columns" :showBottomSum="keys.showBottomSum" :value="list">
				<template #operate="operate" v-if="!keys.disabled">
					<y-button class="del-btn" @click="del(operate)" size="small">删除</y-button>
				</template>
			</y-table>
			<template v-if="!keys.disabled">
				<y-button v-if="!keys.maxlength || list.length < keys.maxlength" class="open-btn" @click="open">添加</y-button>
			</template>
			<y-popup v-model="showPopup">
				<view class="popup-box">
					<!-- <y-form :keys="keys.columns" v-model="info" @submit="submitForm" @change="keys.formChange" submit-text="添加"></y-form> -->
				</view>
			</y-popup>
		</view>
	</view>
</template>

<script>
import yTable from '../y-table/y-table.vue';
import yButton from '../y-button/y-button.vue';
import yPopup from '../y-popup/y-popup.vue';
export default {
	name: 'yTableForm',
	components: {
		yTable,
		yButton,
		yPopup
	},
	props: {
		value: '',
		keys: {},
		showBottomSum: false
	},
	data() {
		return {
			info: {},
			showPopup:false
		};
	},
	computed:{
		list(){
			return this.value || [];
		},
		_keys(){
			const {maxlength,maxLength,...keys} = this.keys;
			return {
				...keys,
				maxlength:maxlength || maxLength
			}
		}
	},
	methods: {
		open() {
			this.keys.reset && (this.info = {});
			this.showPopup = true;
		},
		del({ row, index }) {
			const a = [...this.list];
			a.splice(index, 1);
			const { change } = this.keys;
			typeof change === 'function' && change(a);
			this.$emit('input', a);
		},
		submitForm(e) {
			if (!e) return;
			const { change } = this.keys,
				value = [...this.list, { ...this.info }].filter(x => {
					if (x) return x;
				});
			typeof change === 'function' && change(value);
			this.$emit('input', value);
			this.showPopup = false;
		}
	}
};
</script>

<style scoped lang="scss">
.form-y-table {
	width: 100%;
	padding-top: 5px;
	.open-btn {
		margin: 8px auto 0;
		width: 30%;
		line-height: 1.5em;
		font-size: 16px;
	}
	.del-btn {
		background: #ff4f0a;
	}
	.popup-box {
		max-height: 80vh;
		overflow: hidden;
		overflow-y: auto;
		background-color: #fff;
		border-top-left-radius: 4px;
		border-top-right-radius: 4px;
		box-shadow: 0 2px 5px 0 rgba(255,255,255,.3);
		.y-form {
			border-radius: inherit;
		}
	}
}
</style>
